package com.kyzh.core.download.down

import android.content.Context
import android.util.Log
import androidx.annotation.NonNull
import com.gushenge.core.beans.DownTaskBean
import com.gushenge.core.beans.Game
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.utils.appInstall
import com.liulishuo.okdownload.DownloadTask
import com.liulishuo.okdownload.SpeedCalculator
import com.liulishuo.okdownload.StatusUtil
import com.liulishuo.okdownload.core.Util
import com.liulishuo.okdownload.core.breakpoint.BlockInfo
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo
import com.liulishuo.okdownload.core.cause.EndCause
import com.liulishuo.okdownload.core.cause.EndCause.*
import com.liulishuo.okdownload.core.listener.DownloadListener4WithSpeed
import com.liulishuo.okdownload.core.listener.assist.Listener4SpeedAssistExtend
import java.math.BigDecimal


/**
 *
 * @Author:         yu
 * @CreateDate:     2021/3/17 9:44
 */
open class DownLoadListener(context: Context, game:
DownTaskBean
): DownloadListener4WithSpeed() {
    companion object{
        private const val TAG = "DownLoadListener"
    }
    private val game:
            DownTaskBean=game
    private var totalLength: Long = 0
    private var readableTotalLength: String? = null
    private val context //谨防内存泄漏
            : Context? = context
    override fun taskStart(task: DownloadTask) {
        Log.i(TAG, "【3、taskStart${game.name}】$task  ");
    }

    override fun connectStart(task: DownloadTask, blockIndex: Int, requestHeaderFields: MutableMap<String, MutableList<String>>) {
        Log.i(TAG, "【3、connectStart ${game.name}】$blockIndex  ");
    }

    override fun connectEnd(task: DownloadTask, blockIndex: Int, responseCode: Int, responseHeaderFields: MutableMap<String, MutableList<String>>) {
        Log.i(TAG, "【4、connectEnd ${game.name}】$blockIndex，$responseCode  ");
    }

    override fun taskEnd(task: DownloadTask, cause: EndCause, realCause: Exception?, taskSpeed: SpeedCalculator) {
        Log.i(TAG, "【8、taskEnd  ${game.name}】  " + cause.name + "：" + if (realCause != null) realCause.message else "无异常")
        dealEnd(task,context, game, cause)
    }

    override fun infoReady(task: DownloadTask, info: BreakpointInfo, fromBreakpoint: Boolean, model: Listener4SpeedAssistExtend.Listener4SpeedModel) {
        totalLength = info.totalLength
        readableTotalLength = Util.humanReadableBytes(totalLength, true)
        DownTask.mapDown[task.url]=game
        LiveEventBus.get<Map<String,DownTaskBean>>("GAMETASK").post(DownTask.mapDown)
        Log.i(TAG, "【2、infoReady  $totalLength  --- ${game.name}】当前进度" + info.totalOffset.toFloat() / totalLength * 100 + "%" + "，" + info.toString())
    }

    override fun progressBlock(task: DownloadTask, blockIndex: Int, currentBlockOffset: Long, blockSpeed: SpeedCalculator) {
        Log.i(TAG, "【2、progressBlock   ${game.name}】" )
    }

    override fun progress(task: DownloadTask, currentOffset: Long, taskSpeed: SpeedCalculator) {
        val readableOffset = Util.humanReadableBytes(currentOffset, true)
        val progressStatus = "$readableOffset/$readableTotalLength"
        val speed = taskSpeed.speed()
        val percent = currentOffset.toFloat() / totalLength * 100
//        Log.i(TAG, "【6、progress】$currentOffset[$progressStatus]，速度：$speed，进度：$percent%")
//        DownLoadBean(downLoadBean.name,
//                save2(percent)
//                ,,,1,downLoadBean.packname,downLoadBean.size,currentOffset.toString())
        game.run {
            name=game.name
            process=save2(percent)
            url=game.url
            icon=game.icon
            packageName=game.packageName
            size=game.size
            state = if(StatusUtil.getStatus(task)==StatusUtil.Status.IDLE){
                0
            }else{
                1
            }
        }
        Log.e("TAG", "progress: ", )
        game.updateAll("url = ?", game.url)
        if(StatusUtil.getStatus(task)!= StatusUtil.Status.IDLE){
            DownTask.postValue(game)
        }

        game.process= save2(percent)
    }

    override fun blockEnd(task: DownloadTask, blockIndex: Int, info: BlockInfo?, blockSpeed: SpeedCalculator) {
        Log.i(TAG, "【7、blockEnd】$blockIndex");
    }
   // 0 闲置  1 下载 2 暂停  3下载结束  4打开  5 队列
   fun dealEnd(task: DownloadTask, context: Context?, game:
   DownTaskBean, @NonNull cause: EndCause) {

         when (cause) {
             COMPLETED -> {
                 context?.appInstall( task)
                 game.process = 100f
                 game.state=3
                 game.updateAll("url=?", game.url)
                 DownTask.postValue(game)
                 Log.e(TAG, "dealEnd: COMPLETED", )
             }
             CANCELED -> {
                 Log.e(TAG, "dealEnd:${game.name} CANCELED", )
                 game.state=0
                 if(task.tag=="cancel"){
                     game.state = 4
                     DownTask.mapDown[game.url]=game
                     LiveEventBus.get<Map<String,DownTaskBean>>("GAMETASK").post(DownTask.mapDown)
                     game.delete()
                 }else{
                     game.updateAll("url=?", game.url)
                     DownTask.postValue(game)
                 }

             }
            ERROR ->{
//                downListener.error("下载错误",game)
                Log.e(TAG, "dealEnd: ERROR", )
                game.state=0
                DownTask.postValue(game)
            }
            FILE_BUSY -> {
//                downListener.error("文件被占用",game)
                Log.e(TAG, "dealEnd: FILE_BUSY", )
                game.state=0
                DownTask.postValue(game)
            }
            SAME_TASK_BUSY ->{
//                downListener.waiting(game)
                Log.e(TAG, "dealEnd: SAME_TASK_BUSY", )
                game.state=0
                DownTask.postValue(game)
            }
            PRE_ALLOCATE_FAILED ->{
//                downListener.error("预分配失败",game)
                Log.e(TAG, "dealEnd: PRE_ALLOCATE_FAILED", )
                game.state=0
                DownTask.postValue(game)
            }
        }
    }

    /**
     * 保留兩位小鼠
     */
    fun save2(progress:Float):Float{
        var bd =  BigDecimal(progress.toString())
        bd   =  bd.setScale(2,4);
        return bd.toFloat();
    }
}